package com.moss.cloud.base.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moss.cloud.base.api.model.from.BaseFrom;
import com.moss.cloud.base.api.model.from.SysRoleFrom;
import com.moss.cloud.base.api.model.param.RolePageParam;
import com.moss.cloud.base.biz.mapper.SysRoleMapper;
import com.moss.cloud.base.biz.service.ISysRoleService;
import com.moss.cloud.common.base.model.po.SysRole;
import com.moss.cloud.common.base.utils.PageUtil;
import com.moss.cloud.common.core.constant.Constant;
import com.moss.cloud.common.core.enums.state.Deleted;
import com.moss.cloud.common.core.exception.SystemErrorType;
import com.moss.cloud.common.core.utils.BooleanHandel;
import com.moss.cloud.common.core.utils.UserContextHolder;
import com.moss.cloud.common.security.annotation.RequiresRole;
import com.moss.cloud.common.security.annotation.RequiresTenant;
import com.moss.cloud.common.security.component.RedisTemplateOps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 角色管理服务实现
 *
 * @author 瑾年
 * @date 2023年3月24日
 */
@Slf4j
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {

    private final RedisTemplateOps redisTemplateOps;

    public SysRoleServiceImpl(RedisTemplateOps redisTemplateOps) {
        this.redisTemplateOps = redisTemplateOps;
    }

    /**
     * 根据角色code查询角色
     *
     * @param code
     * @return
     */
    @Override
    public SysRole getSysRole(String code) {
        SysRole sysRole;
        Boolean hasKey = redisTemplateOps.hasKey(Constant.SYS_ROLE + code);
        if (hasKey.equals(Boolean.TRUE)) {
            sysRole = (SysRole) redisTemplateOps.get(Constant.SYS_ROLE + code);
        } else {
            sysRole = this.getOne(new QueryWrapper<SysRole>().lambda().eq(SysRole::getCode, code));
            redisTemplateOps.set(Constant.SYS_ROLE + code, sysRole);
        }
        return sysRole;
    }

    /**
     * 角色ID查询角色信息
     *
     * @param roleId
     * @return
     */
    @Override
    public SysRole roleInfo(Long roleId) {
        return this.getById(roleId);
    }

    /**
     * 获取租户角色列表
     *
     * @return
     */
    @Override
    public List<SysRole> sysRoles() {
        Long tenantId = UserContextHolder.getTenantId();
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        return this.list(createdQueryWrapper(queryWrapper, tenantId));
    }

    private QueryWrapper<SysRole> createdQueryWrapper(QueryWrapper<SysRole> queryWrapper, Long tenantId) {
        BooleanHandel.isTureOrFalse(tenantId.equals(Constant.SUPER_TENANT)).trueOrFalseHandle(() -> {
            List<Long> tenantIds = Arrays.asList(0L, tenantId);
            queryWrapper.lambda().in(SysRole::getTenantId, tenantIds);
        }, () -> queryWrapper.lambda().eq(SysRole::getTenantId, tenantId));
        return queryWrapper;
    }

    /**
     * 分页查询租户角色信息
     *
     * @param rolePageParam
     * @return
     */
    @Override
    @RequiresTenant
    public IPage<SysRole> rolePage(RolePageParam rolePageParam) {
        Long tenantId = UserContextHolder.getTenantId();
        Page<SysRole> page = PageUtil.createPage(rolePageParam.getCurrent(), rolePageParam.getSize());
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().ne(SysRole::getDeleted, Deleted.DELETE.code());
        queryWrapper.lambda().eq(StringUtils.isNotBlank(rolePageParam.getCode()), SysRole::getCode, rolePageParam.getCode());
        queryWrapper.lambda().like(StringUtils.isNotBlank(rolePageParam.getName()), SysRole::getName, rolePageParam.getName());
        queryWrapper.lambda().eq(Objects.nonNull(rolePageParam.getDeleted()), SysRole::getDeleted, rolePageParam.getDeleted());
        return this.page(page, createdQueryWrapper(queryWrapper, tenantId));
    }

    /**
     * 删除角色信息
     *
     * @param baseFrom
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @RequiresTenant
    @RequiresRole
    public Boolean removeRole(BaseFrom baseFrom) {
        SysRole sysRole = this.getById(baseFrom.getId());
        BooleanHandel.trueThrow(Objects.isNull(sysRole)).throwMessage(SystemErrorType.DATE_EMPTY);
        return this.removeById(baseFrom.getId());
    }

    /**
     * 新增角色信息
     *
     * @param sysRoleFrom
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @RequiresTenant
    @RequiresRole
    public Boolean addRole(SysRoleFrom sysRoleFrom) {
        this.checkRoleCode(sysRoleFrom,Boolean.TRUE);
        Long tenantId = UserContextHolder.getTenantId();
        SysRole sysRole = new SysRole();
        BeanUtils.copyProperties(sysRoleFrom, sysRole);
        sysRole.setTenantId(tenantId);
        return this.save(sysRole);
    }

    /**
     * 编辑角色信息
     *
     * @param sysRoleFrom
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @RequiresTenant
    @RequiresRole
    public Boolean updateRole(SysRoleFrom sysRoleFrom){
        BooleanHandel.trueThrow(Objects.isNull(sysRoleFrom.getId())).throwMessage(SystemErrorType.PRIMARY_KEY);
        SysRole roleInfo = this.roleInfo(sysRoleFrom.getId());
        BooleanHandel.trueThrow(Objects.isNull(roleInfo)).throwMessage(SystemErrorType.DATE_EMPTY);
        Long tenantId = UserContextHolder.getTenantId();
        BooleanHandel.trueThrow(!roleInfo.getTenantId().equals(tenantId)).throwMessage(SystemErrorType.DATA_PERMISSION_EXCEPTION);
        this.checkRoleCode(sysRoleFrom,Boolean.FALSE);
        SysRole sysRole = new SysRole();
        BeanUtils.copyProperties(sysRoleFrom, sysRole);
        return this.updateById(sysRole);
    }

    private void checkRoleCode(SysRoleFrom sysRoleFrom, Boolean isAdd) {
        List<SysRole> roles = this.list(new QueryWrapper<SysRole>()
                .lambda().eq(SysRole::getCode, sysRoleFrom.getId()));
        BooleanHandel.trueThrow(CollectionUtils.isNotEmpty(roles)).throwMessage(SystemErrorType.ROLE_CODE_REPEAT);
        BooleanHandel.isTrue(isAdd.equals(Boolean.FALSE)).trueHandle(() -> {
            roles.removeIf(item -> item.getId().equals(sysRoleFrom.getId()));
            BooleanHandel.trueThrow(CollectionUtils.isNotEmpty(roles)).throwMessage(SystemErrorType.ROLE_CODE_REPEAT);
        });
    }

}
